const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const mykey = 'fdskjfoiernknziure8'

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

router.get('/list', async(ctx, next) => {
  await ctx.render('list', {
    title: 'Hello Koa 2!'
  })
})

router.post('/login', async(ctx, next) => {
  let userInfo = ctx.request.body;
  let username = JSON.parse(userInfo).username
  let password = JSON.parse(userInfo).password

  if(username === 'zhangsan' && password === '1234') {
    let token = jwt.sign({'username':username,'password':password},mykey)

    ctx.body = {token,statu:'ok'}
  }
})

router.get('/getdata', async(ctx, next) => {
  let authorization = ctx.req.headers.authorization

  let recoded = jwt.verify(authorization,mykey)

  if(recoded.username) {
    ctx.body = {'status':'success'}
  }
})

module.exports = router
